package com.zpark.utils;

import java.io.Serializable;

/**
 * 统一API响应封装类
 * @param <T> 响应数据类型
 */
public class R<T> implements Serializable {
    private static final long serialVersionUID = 1L;

    // ========== 核心字段 ==========
    private boolean success;
    private int code;       // 业务状态码（推荐使用HTTP状态码或自定义业务码）
    private T data;         // 响应数据
    private String message; // 提示信息
    private String traceId; // 链路追踪ID（微服务场景）

    // ========== 构造方法 ==========
    private R() {}

    // ========== 成功响应 ==========
    public static <T> R<T> success() {
        return success(null);
    }

    public static <T> R<T> success(T data) {
        return new R<T>()
                .setSuccess(true)
                .setCode(200)
                .setData(data)
                .setMessage("操作成功");
    }

    // ========== 失败响应 ==========
    public static <T> R<T> fail(int code, String message) {
        return new R<T>()
                .setSuccess(false)
                .setCode(code)
                .setMessage(message);
    }

    public static <T> R<T> fail(int code, String message, T data) {
        return (R<T>) fail(code, message).setData(data);
    }

    // ========== 链式Setter ==========
    public R<T> setSuccess(boolean success) {
        this.success = success;
        return this;
    }

    public R<T> setCode(int code) {
        this.code = code;
        return this;
    }

    public R<T> setData(T data) {
        this.data = data;
        return this;
    }

    public R<T> setMessage(String message) {
        this.message = message;
        return this;
    }

    public R<T> setTraceId(String traceId) {
        this.traceId = traceId;
        return this;
    }

    // ========== Getter方法 ==========
    public boolean isSuccess() {
        return success;
    }

    public int getCode() {
        return code;
    }

    public T getData() {
        return data;
    }

    public String getMessage() {
        return message;
    }

    public String getTraceId() {
        return traceId;
    }

    // ========== 常用快捷方法 ==========
    public static <T> R<T> notFound() {
        return fail(404, "资源不存在");
    }

    public static <T> R<T> unauthorized() {
        return fail(401, "未授权访问");
    }

    public static <T> R<T> serverError() {
        return fail(500, "服务器内部错误");
    }
}
